package com.vne.skyemart.util;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

public class XMLUtils {

	public static Document loadXMLFile(String fileName)
			throws ParserConfigurationException, SAXException, IOException {

		File f = new File(fileName);
		DocumentBuilderFactory dpf = DocumentBuilderFactory.newInstance();
		DocumentBuilder bd = dpf.newDocumentBuilder();
		Document doc = bd.parse(f);
		return doc;
	}

	public static NodeList getNodesByXpath(String xquery, Document docLoad) {
		try {
			XPath xpath = XPathFactory.newInstance().newXPath();
			NodeList list = (NodeList) xpath.evaluate(xquery, docLoad,
					XPathConstants.NODESET);
			if (list.getLength() > 0) {
				return list;
			}
		} catch (XPathExpressionException ex) {
			Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null,
					ex.getMessage());
		}
		return null;
	}

	public static Element createElementText(Document docLoad, String elementName,
			String elementValue) {
		Element name = docLoad.createElement(elementName);
		Text tValue = docLoad.createTextNode(elementValue);
		name.appendChild(tValue);
		return name;
	}

	public static void writePrettyXML(org.w3c.dom.Document node, String fileName)
			throws java.io.IOException {
		org.jdom.input.DOMBuilder builder = new org.jdom.input.DOMBuilder();
		org.jdom.Document doc1 = builder.build(node);
		org.jdom.output.Format format = org.jdom.output.Format
				.getPrettyFormat();
		org.jdom.output.XMLOutputter output = new org.jdom.output.XMLOutputter(
				format);
		output.output(doc1, new java.io.FileWriter(fileName));
	}
	
}
